package cn.tedu.baidashi.controller;

import cn.tedu.baidashi.exception.ServiceException;
import cn.tedu.baidashi.model.Address;
import cn.tedu.baidashi.service.Impl.AddressServiceImpl;
import cn.tedu.baidashi.vo.AddressVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tedu.cn
 * @since 2022-02-12
 */
@Slf4j
@RestController
//定义requestMapping的路径
@RequestMapping("/portal/address")
public class AddressController {

    @Autowired
    AddressServiceImpl addressService;
    @GetMapping("")
    public List<Address> getAddressOne(
            @AuthenticationPrincipal UserDetails user, AddressVo addressVo
            ){
        List<Address> addresses=addressService.findAddressVoByCustomerName(user);
        return addresses;
    }
    @GetMapping("/{id}/delete")
    public String removeAddress(
            @AuthenticationPrincipal UserDetails user,
            @PathVariable Integer id
    ){
        Boolean b=addressService.removeAddress(id,user.getUsername());
        System.out.println(b);
        if(b){
            return "删除成功了";
        }else {
            return "删除失败了";
        }

    }
    @GetMapping("/{id}/getForm")
    public Address getForm(
            @PathVariable Integer id
    ){
        Address address=addressService.selectAddressToFormById(id);
        return address;

    }
    @GetMapping("/{id}/update")
    public Address update(
        @PathVariable Integer id,
        @Validated AddressVo addressVo,
        BindingResult result,
        @AuthenticationPrincipal UserDetails user

    ){
        log.debug("表单信息为：",addressVo);
        log.debug("id为",id);
        if(result.hasErrors()){
            String msg=result.getFieldError().getDefaultMessage();
            throw new ServiceException(msg);
        }

        return null;
    }

}
